// 购物车仓库
import http from '@/serveies/api/request'
import { Toast } from 'mint-ui'
export default {
  state: {
    list: [],
    selectedList: []
  },
  getters: {
    // 计算总价数量
    total (state) {
      const total = {
        count: 0,
        num: 0
      }
      state.list.forEach(v => {
        if (v.checked) {
          total.count += parseFloat(v.goods_num * v.goods_price)
          total.num += parseInt(v.goods_num)
        }
      })
      return total
    }
  },
  mutations: {
    initGetData (state, cartArr) {
      state.list = cartArr
      cartArr.forEach(v => {
        if (v.checked) {
          state.selectedList.push(v.id)
        }
      })
    },
    deleteGoods (state, id) {
      state.list = state.list.filter(v => {
        return v.id !== id
      })
    },
    selectItem (state, index) {
      const id = state.list[index].id
      const i = state.selectedList.indexOf(id)
      if (i > -1) {
        state.list[index].checked = false
        return state.selectedList.splice(i, 1)
      } else {
        // 没有选中
        state.list[index].checked = true
        state.selectedList.push(id)
      }
    }
  },
  actions: {
    deleteGoodsFn ({ commit }, id) {
      http
        .$axios({
          url: '/api/deleteCart',
          method: 'post',
          headers: {
            token: true
          },
          data: {
            id
          }
        })
        .then((res) => {
          if (res.success) {
            commit('deleteGoods', id)
            Toast(res.msg)
          }
        })
    },
    selectBtnFn ({ commit }, id) {
      commit('selectBtn', id)
    }
  }
}
